﻿$(function () {
    $("#getMore").live('click', function () {
        var articleid = $("#PostedComment_ArticleID").val();
        var currentPage = $("#currentPage").val();
        getMoreComments(articleid, currentPage++);

        $("#currentPage").val(currentPage);
    });
});

function getMoreComments(articleid, page) {
    
    $.getJSON("/Comments/GetMoreComments",
    {
        articleid: articleid,
        page: page
    }, function (data) {
        var currentRecords = parseInt($("#currentCount").html());
        currentRecords += data.Comments.length;
        $("#currentCount").html(currentRecords);

        if (currentRecords == parseInt(data.TotalComments)) {
            $("#getMore").hide();
        }

        $.each(data.Comments, function (i, comment) {
            $("#posts").append(getCommentMarkup(comment.PostedBy, comment.PostDate, comment.Comment, i)).children(':last').hide().fadeIn(2000);
        });
    });
}

function getCommentMarkup(userName, date, message, index) {
    var backgroundClass = index % 2 == 1 ? "commentLight" : "commentDark";
    var $markup = '<div class="' + backgroundClass + '">' +
                      '<div class="commentBy"><strong>' + userName + '</strong></div>' +
                      '<div class="commentPosted">' + date + '</div>' +
                      '<div class="commentMessage">' + message + '</div>' +
                  '</div>';

    return $markup;
}

$('#counter').html($('#PostedComment_Message').val().length + ' characters');

$("#postComment").live('click', function () {
    if ($('#PostedComment_Message').val().length < 1) {

        $("#errorMessage").slideDown('slow');
        setTimeout(function () { $("#errorMessage").slideUp('slow'); }, 5000);
        return false;
    }
});

$('#PostedComment_Message').live('keyup', function () {
    $('#counter').html($(this).val().length + ' characters');

    if ($(this).val().length > 1000) {
        $("#maxChars").removeClass("maxChars").addClass("overMaxChars");
        $("#postComment").fadeOut('slow');
    }
    else if ($("#maxChars").hasClass("overMaxChars")) {
        if($("#postComment").is(":hidden")){
            $("#postComment").fadeIn('normal');
        }
        $("#maxChars").removeClass("overMaxChars").addClass("maxChars");
    }
});